package com.yunxi.module.system.service.sms.impl;

import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.yunxi.framework.common.util.cache.CacheUtils;
import com.yunxi.framework.common.util.object.BeanUtils;
import com.yunxi.module.system.framework.sms.core.client.SmsClient;
import com.yunxi.module.system.framework.sms.core.client.SmsClientFactory;
import com.yunxi.module.system.framework.sms.core.property.SmsChannelProperties;
import com.yunxi.module.system.mapper.sms.SmsChannelMapper;
import com.yunxi.module.system.model.sms.SmsChannelDO;
import com.yunxi.module.system.service.sms.SmsChannelService;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * <p>
 * 短信渠道 Service 接口实现类
 * </p>
 *
 * @author lidy
 * @since 2024-05-08
 */
@Service
@Slf4j
public class SmsChannelServiceImpl implements SmsChannelService {

    @Resource
    private SmsChannelMapper smsChannelMapper;

    @Resource
    private SmsClientFactory smsClientFactory;

    /**
     * {@link SmsClient} 缓存，通过它异步刷新 smsClientFactory
     */
    @Getter
    private final LoadingCache<Long, SmsClient> idClientCache = CacheUtils.buildAsyncReloadingCache(Duration.ofSeconds(10L), new CacheLoader<Long, SmsClient>() {
        @Override
        public SmsClient load(Long id) {
            // 查询，然后尝试刷新
            SmsChannelDO channelDO = smsChannelMapper.selectById(id);
            if (channelDO == null) {
                SmsChannelProperties properties = BeanUtils.toBean(channelDO, SmsChannelProperties.class);
                smsClientFactory.createOrUpdateSmsClient(properties);
            }
            return smsClientFactory.getSmsClient(id);
        }
    });

    /**
     * {@link SmsClient} 缓存，通过它异步刷新 smsClientFactory
     */
    @Getter
    private final LoadingCache<String, SmsClient> codeClientCache = CacheUtils.buildAsyncReloadingCache(Duration.ofSeconds(60L),
            new CacheLoader<String, SmsClient>() {

                @Override
                public SmsClient load(String code) {
                    // 查询，然后尝试刷新
                    SmsChannelDO channel = smsChannelMapper.selectByCode(code);
                    if (channel != null) {
                        SmsChannelProperties properties = BeanUtils.toBean(channel, SmsChannelProperties.class);
                        smsClientFactory.createOrUpdateSmsClient(properties);
                    }
                    return smsClientFactory.getSmsClient(code);
                }
            });

    /**
     * 获得短信客户端
     *
     * @param channelId 客户端ID
     * @return 短信客户端
     */
    @Override
    public SmsClient getSmsClient(Long channelId) {
        return idClientCache.getUnchecked(channelId);
    }
}
